package com.lzy.config;

import com.lzy.common.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 对于OPTIONS请求直接放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        
        // 如果路径是登录或注册，不需要验证token
        String uri = request.getRequestURI();
        if (uri.contains("/user/login") || uri.contains("/user/register")) {
            return true;
        }
        
        // 验证token
        if (token != null && token.startsWith("Bearer ")) {
            // 去掉Bearer 前缀
            token = token.substring(7);
            try {
                // 验证token
                String username = jwtUtil.getUsernameFromToken(token);
                if (username != null && jwtUtil.validateToken(token, username)) {
                    // 将用户名存入请求属性，方便后续使用
                    request.setAttribute("username", username);
                    return true;
                }
            } catch (Exception e) {
                log.error("JWT验证失败: {}", e.getMessage());
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\":401,\"message\":\"身份验证失败，请重新登录\"}");
                return false;
            }
        }
        
        // 如果没有token或token无效，返回401未授权
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"请先登录\"}");
        return false;
    }
} 